import { Button, Card, Flex, Select } from "antd";
import React, { useEffect, useState } from "react"
import conn from '../conn/conn';
import { runProg } from "../conn/utils";

const SerialPortSetting: React.FC = () => {

  let [ports, setPorts] = useState<string[]>([])
  let [port, setPort] = useState("");
  const [openText, setOpenText] = useState('打开');

  const updateOpenText = async () => {
    if (await conn.isOpen()) {
      setOpenText("关闭");
    } else {
      setOpenText('打开');
    }
  }

  let onClickRefresh = async () => {
    const ports = await conn.activePorts();
    setPorts(ports);
    if (ports.length != 0) {
      setPort(ports[0]);
    }
    await updateOpenText();
  }

  const openPort = async () => {
    await runProg("打开串口", async () => {
      if (port.length == 0) {
        throw '串口没有';
      }
      await conn.open(port);
    });
  }

  const closePort = async () => {
    await runProg('关闭串口', async () => {
      await conn.close();
    })
  }

  let onClickOpen = async () => {
    if (await conn.isOpen()) {
      await closePort();
    } else {
      await openPort();
    }
    await updateOpenText();
  }

  useEffect(() => {
    onClickRefresh();
  }, []);

  return (
    <>
      <Card title={"串口设置"}>
        <Flex vertical={true} gap={10} align={"center"}>
          <Flex vertical={false} gap={5} align={"center"}>
            <p>端口:</p>
            <Select value={port} onChange={(e) => setPort(e)} style={{ minWidth: '90px' }}>
              {ports.map((item, index) => (<Select.Option key={index} label={item}>{item}</Select.Option>))}
            </Select>
          </Flex>

          <Flex vertical={false} gap={10}>
            <Button onClick={onClickRefresh} >刷新</Button>
            <Button onClick={onClickOpen} type="primary">{openText}</Button>
          </Flex>
        </Flex>
      </Card>
    </>

  )
}



export default SerialPortSetting;
